package cn.com.fattiger.framework.remoting.netty4.client.channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import cn.com.fattiger.framework.remoting.netty4.client.coder.ClientDecoder;
import cn.com.fattiger.framework.remoting.netty4.client.coder.ClientEncoder;
import cn.com.fattiger.framework.remoting.netty4.client.handle.ClientHandlerAdapter;
import cn.com.fattiger.framework.remoting.netty4.common.protocol.handle.ReceivedHandle;

public class ClientChannelInitializer extends ChannelInitializer<SocketChannel> {
	private final String hostName;
	private final ReceivedHandle receivedHandle;

	public ClientChannelInitializer(String hostName, ReceivedHandle receivedHandle) {
		super();
		this.hostName = hostName;
		this.receivedHandle = receivedHandle;
	}

	@Override
	protected void initChannel(SocketChannel arg0) throws Exception {
		// TODO Auto-generated method stub
		ChannelPipeline p = arg0.pipeline();
		// p.addLast(new LengthFieldPrepender(4));
		// p.addLast(new ClientRequestEncoder(protocol));
		// p.addLast(new ClientRequestDecoder(protocol));
		// p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));

		p.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		p.addLast(new LengthFieldPrepender(4));
		// pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
		// pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
		p.addLast(new ClientEncoder());// 编码
		p.addLast(new ClientDecoder());// 解码
		p.addLast(new IdleStateHandler(0, 30, 0));
		p.addLast(new ClientHandlerAdapter(hostName, receivedHandle));
	}

}
